<template>
	<view v-if="showUploadData">
		<view class="picshowContainers">
			<view class="picshowContainers_item">

				<view class="picshowContainers_title">
					病史资料图片
				</view>
				<!-- :handle="'.defaultTypeTag'" -->
				<view class="picshowContainers_pic_containers">
					<draggable v-model="dialogImages" :options="dragOptions" class="dragArea" @end="getImgSortArr()">
						<view class="picshowContainers_pic_containers_item" v-for="(item, index) in dialogImages"
							:key="index">
							<image :src="item.url" class='picshowContainers_pic_containers_item_img defaultTypeTag'
								mode="aspectFit">
							</image>
							<view class="imgPoint" @tap="showBigImg(index)">

							</view>
							<view class="closeIcon" @tap.stop=''>
								<u-icon name="close-circle-fill" color="#2979ff" size="28rpx"
									@tap="deletePic(index)"></u-icon>
							</view>

						</view>
					</draggable>
					<!-- :fileList="dialogImages" @delete="deletePic" :previewFullImage="true" -->
					<u-upload :fileList="[]" @afterRead="afterRead" multiple :maxCount="10"
						:capture="['album', 'camera']"></u-upload>
				</view>
			</view>
			<view class="picshowContainers_item">
				<view class="picshowContainers_title">
					PDF资料:
				</view>
				<view class="picshowContainers_pic_containers" v-if="isToken">
					<u-upload @afterRead="afterfile" :maxCount="10" accept=".pdf">
						<view class="picshowContainers_btn">
							pdf上传
						</view>
					</u-upload>

				</view>

			</view>
			<view class="picshowContainers_pic_list">
				<view class="picshowContainers_pic_list_item" v-for="(item, index) in pdfSrcList" :key="index">
					<view class="picshowContainers_pic_list_item_name" @tap="downloadFile(item)">
						{{item.name}} <text class="picshowContainers_pic_list_item_btn" v-if="isToken"
							@tap.stop="deletefile(index)">删除</text>
					</view>

					<u-line-progress :percentage="item.schedule" height="14rpx" activeColor="#226eff"
						v-if="item.schedule&&item.schedule!='100'"></u-line-progress>
				</view>
			</view>

		</view>
		<view class="popupGroup" v-if="isToken">
			<view class="popupGroup_btn success right" v-if="dialogImages&&dialogImages.length>0"
				@tap="showimgdialogVisible">
				病史资料排序整理
			</view>
			<view class="popupGroup_btn primary" @tap="comfire">
				提交
			</view>
		</view>
		<u-overlay :show="imgdialogVisible" @click="''" zIndex='100'>
			<u-popup :show="imgdialogVisible" :closeOnClickOverlay='false' closeable mode='center'
				@close="imgdialogVisible=false" :round="8" :customStyle="{width:'95%', padding:'30px 10px 10px'}">
				<view class="popupContent">
					<view class="popupContent_pic_containers">
						<draggable v-model="dialogImages" :options="dragOptions" class="dragArea"
							@end="getImgSortArr()">
							<view class="popupContent_pic_containers_item" v-for="(item, index) in dialogImages"
								:key="index">

								<image :src="item.url" class='popupContent_pic_containers_item_img defaultTypeTag'
									mode="aspectFit">
								</image>
								<view class="imgPoint" @tap="showBigImg(index)">

								</view>
							</view>
						</draggable>
					</view>
				</view>
			</u-popup>

		</u-overlay>

	</view>
</template>

<script>
	export default {
		components: {

		},
		name: "extroUpload",
		props: ['extroUploadInfos', 'pafArr', 'imgArr', 'createDiagnosisDataParameters'], //entranceType  1:专家介绍进入 2:特需会诊进入
		data() {
			return {
				drag: false,
				dragOptions: {
					animation: 200,
					handle: '.defaultTypeTag'
				},
				TransferData: '',
				showUploadData: false,
				lookshowUploadData: false,
				dialogImages: [],
				imageURL: this.imageServiceURL, // 图片上传地址:
				srcList: [],
				pdfSrcList: [],
				imgURL: '',
				createDiagnosisDataParametersArr: [],
				isToken: false,
				imgdialogVisible: false, // 资料排序整理

			}
		},
		created() {

		},
		mounted() {
			if (this.$store.state.user.token) {
				this.isToken = true
			} else {
				this.isToken = false
			}
			this.picopen()
		},
		methods: {
			showimgdialogVisible() {
				this.imgdialogVisible = true
			},
			getImgSortArr() {
				let data = this.dialogImages
				let data1 = this.createDiagnosisDataParametersArr
				this.createDiagnosisDataParametersArr = []
				this.srcList = []
				data.forEach(ele => {
					let obj = data1.find(
						item => item.url == ele.url
					)
					this.srcList.push(obj.url)
					this.createDiagnosisDataParametersArr.push(obj)
				})
				console.log(data)
				console.log(this.createDiagnosisDataParametersArr)


			},
			showBigImg(index) {
				// this.$u.toast('显示大图');
				// console.log(this.srcList)
				uni.previewImage({
					current: index,
					urls: this.srcList
				})
			},
			comfire() {
				let data = {
					orders: this.extroUploadInfos,
					createDiagnosisDataParameters: this.createDiagnosisDataParametersArr,
					imgURL: this.getImages(),
					pdfSrcList: this.getpdfSrcList()
				}
				console.log(data)
				this.$emit('comfire', data)
				// this.showUploadData = false

			},
			getpdfSrcList() {
				let data = []
				let pdfSrcListData = this.pdfSrcList
				pdfSrcListData.forEach(ele => {
					let obj = {
						url: ele.url,
						name: ele.name,
						description: '',
						uuid: this.extroUploadInfos.uuid ? this.extroUploadInfos.uuid : ''
					}
					data.push(obj)
				})
				return data
			},
			getImages() {
				this.imgURL = ''
				this.dialogImages.forEach(ele => {
					this.imgURL += `${ele.url.slice(ele.url.indexOf('_') - 1)}|`
				})
				console.log(this.imgURL)
				return this.imgURL
			},
			// 新增文件
			async afterfile(event) {
				if (event.file.type !== 'application/pdf') {
					this.$u.toast('请上传PDF文件');
					return false; // 不允许上传
				}
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let fileListLen = this[`pdfSrcList`].length
				let item = event.file
				this[`pdfSrcList`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
				console.log(item)
				const result = await this.uploadFilePromise(item.url, fileListLen, 'file')
				console.log(fileListLen)
				let objItem = this[`pdfSrcList`][fileListLen]
				let resultItem = Object.assign(objItem, {
					status: 'success',
					message: '',
					url: result
				})
				this.getcreateDiagnosisDataParametersArr(resultItem, 'file')
				this[`pdfSrcList`].splice(fileListLen, 1, resultItem)

			},
			// 下载
			// 下载文件资源到本地，客户端直接发起一个 HTTP GET 请求，返回文件的本地临时路径。
			downloadFile(item) {
				if (item.schedule && item.schedule != 100) {
					this.$u.toast('请等待文件上传成功之后，再预览~');
					return false
				}
				const downloadLink = item.url;
				window.open(downloadLink, '_blank'); //h5直接进行跳转页面打开就可以了
				uni.downloadFile({ //调用uni中的下载方法
					url: item.url, //后端返回的完整路径
					success: (res) => {
						console.log(res.tempFilePath, "下载");
						if (res.statusCode === 200) {
							const tempFilePath = res.tempFilePath;
							// 显示文件
							uni.openDocument({
								filePath: tempFilePath,
								success: (res) => {
									console.log(res, '打开文件成功');
								},
							});
						}
					},
					fail: (err) => {
						console.log('下载文件失败', err);
					}
				});
			},
			//删除文件
			deletefile(index) {
				this[`pdfSrcList`].splice(index, 1)
				let pdfItem = this[`pdfSrcList`][index]
				this.createDiagnosisDataParametersArr = this.createDiagnosisDataParametersArr.filter(
					item => item.url != pdfItem.url
				)
			},
			// 删除图片
			deletePic(index) {
				//this.$u.toast('删除大图');
				let imgItem = this[`dialogImages`][index]
				this[`dialogImages`].splice(index, 1)
				this.srcList.splice(index, 1)
				this.createDiagnosisDataParametersArr = this.createDiagnosisDataParametersArr.filter(
					item => item.url != imgItem.url
				)
			},
			getcreateDiagnosisDataParametersArr(data, type) {
				this.createDiagnosisDataParametersArr.push({
					url: data.url,
					name: data.name,
					fileType: type == 'file' ? 5 : 0,
					description: '',
					uid: data.uid
				})
			},
			// 新增图片
			async afterRead(event) {

				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`dialogImages`].length
				console.log(fileListLen)
				lists.map((item) => {
					this[`dialogImages`].push({
						...item,
						schedule: 0,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, i, 'img')
					console.log(fileListLen)
					let item = this[`dialogImages`][fileListLen]
					console.log(result)
					let resultItem = Object.assign(item, {
						status: 'success',
						message: '',
						schedule: 100,
						url: result
					})
					this.getcreateDiagnosisDataParametersArr(resultItem, 'img')
					this[`dialogImages`].splice(fileListLen, 1, resultItem)
					this.srcList.splice(fileListLen, 1, result)
					fileListLen++
				}
			},
			uploadFilePromise(url, index, type) {
				let that = this
				return new Promise((resolve, reject) => {
					let uploadTask = uni.uploadFile({
						url: `${that.imageURL}/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {

						},
						success: (res) => {
							console.log(res)
							let data = JSON.parse(res.data)

							setTimeout(() => {
								console.log(data.url)
								resolve(data.url)
							}, 1000)
						}
					});
					uploadTask.onProgressUpdate((res) => {
						// console.log('上传进度' + res.progress);
						// console.log('已经上传的数据长度' + res.totalBytesSent);
						// console.log('预期需要上传的数据总长度' + res
						// 	.totalBytesExpectedToSend);
						let item
						if (type == 'img') { //图片上传
							item = that[`dialogImages`][index]
							that[`dialogImages`].splice(index, 1, Object.assign(item, {
								status: 'success',
								message: '',
								schedule: res.progress,

							}))
						} else {
							item = that[`pdfSrcList`][index]

							that[`pdfSrcList`].splice(index, 1, Object.assign(item, {
								status: 'success',
								message: '',
								schedule: res.progress,

							}))
						}
						// 测试条件，取消上传任务。
						if (res.progress > 50000) {
							uploadTask.abort();
						}
					});

				})
			},
			picopen() { //图片上传弹窗打开时
				this.dialogImages = this.imgArr
				this.pdfSrcList = this.pafArr
				this.createDiagnosisDataParametersArr = this.createDiagnosisDataParameters
				this.srcList = []
				this.dialogImages.forEach(ele => {
					this.srcList.push(ele.url)
				})
				this.showUploadData = true
			},
			picClose() { //图片上传弹窗关闭
				// this.showUploadData = false
				this.$emit('closeedextroUploadStatus')

			},


		}
	}
</script>

<style lang="scss" scoped>
	// 上传弹窗
	.dragArea {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.closeIcon {
		position: absolute;
		top: 2rpx;
		right: 2rpx;
	}

	.picshowContainers {
		&_item {
			display: flex;
			margin-top: 20rpx;
		}

		&_title {
			width: 140rpx;
			font-size: 30rpx;
			font-weight: 700;
			line-height: 44rpx;
		}

		&_pic {
			&_containers {
				width: calc(100% - 140rpx);
				display: flex;
				align-items: center;
				flex-wrap: wrap;

				&_item {
					width: 140rpx;
					height: 140rpx;
					background-color: #f4f5f7;
					margin: 0 8rpx 8rpx 0;
					position: relative;

					&_img {
						width: 100%;
						height: 100%;
					}

					.imgPoint {
						position: absolute;
						width: 30rpx;
						height: 30rpx;
						left: 50%;
						top: 50%;
						transform: translate(-50%, -50%);
					}
				}
			}

			&_list {
				&_item {
					&_name {
						font-size: 24rpx;
						line-height: 40rpx;
					}

					&_btn {
						color: red;
						margin-left: 12rpx;
						cursor: pointer;
					}
				}
			}
		}

		&_btn {
			background: #226eff;
			color: #fff;
			padding: 0 16rpx;
			font-size: 26rpx;
			line-height: 44rpx;
		}
	}

	.popupContent {
		height: 80vh;
		overflow-y: auto;

		&_pic {
			&_containers {
				width: calc(100% - 40rpx);
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				justify-content: space-between;

				&_item {
					width: 250rpx;
					height: 250rpx;
					background-color: #f4f5f7;
					margin: 0 8rpx 8rpx 0;
					position: relative;

					&_img {
						width: 100%;
						height: 100%;
					}

					.imgPoint {
						position: absolute;
						width: 50rpx;
						height: 50rpx;
						left: 50%;
						top: 50%;
						transform: translate(-50%, -50%);
					}
				}
			}
		}
	}

	.popupGroup {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24rpx;
		padding-bottom: 24rpx;

		&_btn {
			font-size: 26rpx;
			padding: 8rpx 16rpx;
			border: 2rpx solid #ddd;
			border-radius: 6rpx;
		}

		&_btn.primary {
			color: #fff;
			background: #226eff;
			border: 2rpx solid #226eff;
			border-radius: 6rpx;
		}

		&_btn.success {
			color: #fff;
			background: #67c23a;
			border: 2rpx solid #67c23a;
			border-radius: 6rpx;
		}

		&_btn.right {
			margin-right: 24rpx;
		}
	}

	.btnBox {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24rpx;
		padding-bottom: 24rpx;

		.btn {
			.custom-style {
				padding: 8rpx 16rpx;
				font-size: 30rpx;
			}
		}
		.right {
			margin-right: 24rpx;
		}
	}
</style>